package elion.com.theElion.chartline;

import android.app.Activity;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.WindowManager;


import java.util.ArrayList;
import java.util.List;


import elion.com.theElion.util.HttpUtils;
import elion.com.theElion.util.JsonUtils;
import elion.com.theElion.util.UIHelper;

import elion.com.elion.R;
import elion.com.theElion.util.ReflectUtil;
import lecho.lib.hellocharts.formatter.LineChartValueFormatter;
import lecho.lib.hellocharts.formatter.SimpleLineChartValueFormatter;
import lecho.lib.hellocharts.gesture.ContainerScrollType;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;

public class LineActivity extends Activity
{

    private static LineChartView lineChartView;
    private Axis axisX;
    private Axis axisY;
    private static List<Object> dataList;
    private static List<Float> data ;//數據
    private static List<String> date ;//X坐標值
    private List<PointValue> mPointValues = new ArrayList<>();
    private List<AxisValue> mAxisValues = new ArrayList<>();
    private double max;
    private double min;

    private LineDataAsy asy;

//    private final static String basePackage = "com.example.alex.myapplication.vo.";
    private static String landId;//landId类型
    private static String type;//bean类型
    private static String fieldName;//参数名称
    private static Integer number; //列表长度
    private String path;//url


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_datashower_line);
        setWindow();
        lineChartView = (LineChartView) findViewById(R.id.line);

        //设置动画
        overridePendingTransition(R.anim.modal_in,R.anim.modal_out);

        //设置参数
        Bundle bundle = this.getIntent().getExtras();
        String type1 = bundle.getString("TYPE");
        String nLandId = bundle.getString("LANDID");
        fieldName = bundle.getString("FIELD_NAME");
        //如果查询的同一个bean类中的字段，不重新执行异步
        if( type == null || !type.equals(type1) || date.size() == 0||!landId.equals(nLandId))
        {
            if(data != null && !data.isEmpty()){
                data.clear();
            }
            if(date != null && !date.isEmpty()){
                date.clear();
            }
            if(dataList != null && !dataList.isEmpty()){
                dataList.clear();
            }
            type = bundle.getString("TYPE");
            landId = bundle.getString("LANDID");
//            Log.e("TAG",type);
            asy = new LineDataAsy(type);
//            asy.setCallBack(LineActivity.this);
            number = bundle.getInt("NUMBER", 12);
            path = bundle.getString("PATH");
            asy.execute(path);
        }else
        {
            initPoints(dataList);
            getAxisXlables();
            getAxisPoints();
            initLineChart(max);
        }

    }


    private void setWindow()
    {

        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 为获取屏幕宽、高

        WindowManager.LayoutParams p = getWindow().getAttributes(); // 获取对话框当前的参数值
        p.height = (int) (d.getHeight() * 0.8); // 高度设置为屏幕的1.0
        p.width = (int) (d.getWidth() * 0.9); // 宽度设置为屏幕的0.8
        p.alpha = 1.0f; // 设置本身透明度
        p.dimAmount = 0.2f; // 设置黑暗度

        getWindow().setAttributes(p); // 设置生效
        getWindow().setGravity(Gravity.CENTER);
        getWindow().setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_dialog));
    }
    public void setItem(List<Object> list) {
//        Log.e("TAG","setItem");
        initPoints(list);
        getAxisXlables();
        getAxisPoints();
        initLineChart(max);
    }

    private void initLineChart(double max)
    {
        LineChartValueFormatter formatter = new SimpleLineChartValueFormatter(2);
        Line line = new Line(mPointValues).setColor(Color.BLACK);
        line.setPointColor(Color.parseColor("#46916c"));
        line.setFormatter(formatter);
        List<Line> lines = new ArrayList<>();
        line.setShape(ValueShape.CIRCLE);//点的形状
        line.setPointRadius(5);
//        line.setCubic(true);//設置圓滑
        line.setHasLabels(true);
        line.setHasLines(true);
        line.setHasPoints(true);
        lines.add(line);

        LineChartData data = new LineChartData();//设置参数
        data.setLines(lines);

        setAxisX();
        data.setAxisXBottom(axisX);

        setAxisY();
        data.setAxisYLeft(axisY);
        lineChartView.setLineChartData(data);

        lineChartView.setInteractive(true);//设置交互
        lineChartView.setZoomType(ZoomType.HORIZONTAL);
        lineChartView.setContainerScrollEnabled(true, ContainerScrollType.HORIZONTAL);

        Viewport v1 = new Viewport(lineChartView.getMaximumViewport());

        v1.bottom = 0;
        v1.top = (float) (v1.top + max);
        lineChartView.setMaximumViewport(v1);   //给最大的视图设置 相当于原图
        lineChartView.setCurrentViewport(v1);
        Viewport v2 = new Viewport(lineChartView.getMaximumViewport());
        v2.left = 0;
        v2.right = 5;
        lineChartView.setCurrentViewport(v2);
    }

    private void getAxisXlables() {
        int i = 0;
        for(String value:date) {
            mAxisValues.add(new AxisValue(i).setLabel(value));
            i++;
        }
    }

    private void getAxisPoints() {
        int i = 0;

        for(Float value:data){
            mPointValues.add(new PointValue(i,value));
            i++;
        }
    }

    private void setAxisX(){
        axisX = new Axis();//X轴
        axisX.setLineColor(Color.BLACK);
        axisX.setTextColor(Color.BLACK);
        axisX.setMaxLabelChars(number);
//        axisX.setHasTiltedLabels(true); //坐标斜向显示
        axisX.setValues(mAxisValues);
    }

    private void setAxisY(){
        axisY = new Axis();
        axisY.setHasLines(true);
        axisY.setTextColor(Color.BLACK);
    }

    private void initPoints(List<Object> list){
        date = new ArrayList<>();
        data = new ArrayList<>();
        dataList = list;
        String d;
        float da;
        try {
            for(Object e:list){
                d = (String) ReflectUtil.useGetMethod(e,"date");
                d = d.substring(5,16);
                date.add(d);
                da = Float.parseFloat((String) ReflectUtil.useGetMethod(e,fieldName));
                if(da > max) max = da;
                if(da < min) min = da;
                data.add(da);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        max = setTop(Double.valueOf(max));
    }

    private Double setTop(Double x){
        if(x >= 1){
            x = Math.pow(10,getBit(x)-1)*2;
        }else{
            x = 0.0;
        }
        return x;
    }

    private static int getBit(double x){
        int count = 1;
        while((int)(x/10) != 0){
            count ++;
            x /= 10;
        }
        return count;
    }


    /**
     * Created by Alex on 2017/6/9.
     */

    private class LineDataAsy extends AsyncTask<String,Void,String>
    {
        private List<Object> list = new ArrayList<>();
        private String className;

        public LineDataAsy(String className) {
            this.className = className;
            Log.e("CLASSNAME",className);
        }

        @Override
        protected String doInBackground(String... params)
        {
            return HttpUtils.sendPostMethod(params[0],"utf-8");
        }

        @Override
        protected void onPostExecute(String s)
        {
            super.onPostExecute(s);
            if(s == null) {
                list = null;
            }else
            {
                try
                {
                    list = (List<Object>) JsonUtils.jsonToList(className,s);
                    setItem(list);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            new UIHelper().hideDialogForLoading();

        }

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            new UIHelper().showDialogForLoading(LineActivity.this, "正在加载...", true);
        }

    }

}
